<template>
  <el-card shadow="hover">
    <el-descriptions
      class="margin-top"
      title="开票信息"
      :column="3"
      :size="size"
      border
    />
    <div style="padding-bottom: 10px">
      <el-table v-loading="listLoading" :data="InvoicingList" show-summary>
        <el-table-column
          align="center"
          label="开票ID"
          prop="InvoicingID"
          show-overflow-tooltip
          width="70"
        />
        <el-table-column align="center" label="开票类型" width="120">
          <template #default="{ row }">
            <el-text>{{ row.InvoicingTypeName }}</el-text>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="发票号" width="120">
          <template #default="{ row }">
            <el-text>{{ row.InvoicingCode }}</el-text>
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="开票金额" width="120">
          <template #default="{ row }">
            <el-text>{{ row.InvoicingMoney }}</el-text>
          </template>
        </el-table-column>
        <el-table-column align="center" label="客户方单位">
          <template #default="{ row }">
            <el-text>{{ row.CustomerCompanyName }}</el-text>
          </template>
        </el-table-column>
        <el-table-column align="center" label="纳税人识别号">
          <template #default="{ row }">
            <el-text>{{ row.CustomerLicenseCode }}</el-text>
          </template>
        </el-table-column>
        <el-table-column align="center" label="开票方单位">
          <template #default="{ row }">
            <el-text>{{ row.MyCompanyName }}</el-text>
          </template>
        </el-table-column>
        <el-table-column align="center" label="附件">
          <template #default="{ row }">
            <el-button
              :type="
                row.InvoicingFiles &&
                JSON.parse(row.InvoicingFiles)?.length != 0
                  ? 'success'
                  : 'danger'
              "
              size="small"
              @click="upFiles(row)"
            >
              税务会计上传发票附件
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          v-if="OrderFlowState === 1"
          align="center"
          label="操作"
          width="180"
        >
          <template #default="{ row }">
            <el-button type="success" size="small" @click="invoicingEdit(row)">
              修改
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          v-if="OrderFlowState >= 2 && pageflow === 3"
          align="center"
          label="操作"
          width="180"
        >
          <template #default="{ row }">
            <el-button
              v-if="row.InvoicingState == 0"
              type="danger"
              size="small"
              @click="paymentConfirm(row)"
            >
              确认开票
            </el-button>
            <el-button v-else type="success" size="small">
              {{ row.InvoicStaffName }}已确认开票
            </el-button>
          </template>
        </el-table-column>
        <el-table-column v-else align="center" label="开票确认">
          <template #default="{ row }">
            <el-text v-if="row.InvoicingState == 0" type="danger" size="small">
              新开票待确认
            </el-text>
            <el-text v-else type="success" size="small">
              {{ row.InvoicStaffName }}已确认开票
            </el-text>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <vab-query-form
      v-if="OrderFlowState === 1 || OrderFenqi === 1"
      style="padding: 10px"
    >
      <el-form ref="formRef" :model="InvoicingForm" :rules="rules">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="需开票类型" required prop="InvoicingType">
              <el-select v-model="InvoicingForm.InvoicingType">
                <el-option
                  v-for="(item, index) in InvoicingTypes"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-space>
              <el-form-item
                label="合同归属公司(客户)"
                required
                prop="CustomerLicenseID"
              >
                <el-select
                  v-model="InvoicingForm.CustomerLicenseID"
                  style="width: 250px"
                  @change="getCustomerLicense"
                >
                  <el-option label="新增一个开票信息" :value="0" />
                  <el-option
                    v-for="(item, index) in CustomerLicenseList"
                    :key="index"
                    :label="item.CompanyAllName"
                    :value="item.LicenseID"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                v-if="InvoicingForm.CustomerLicenseID == 0"
                label-width="10"
                required
                prop="CustomerCompanyName"
              >
                <el-input
                  v-model="InvoicingForm.CustomerCompanyName"
                  placeholder="请填写开票客户全称"
                />
              </el-form-item>
            </el-space>
          </el-col>
          <el-col :span="7">
            <el-form-item
              label="纳税人识别号(客户)"
              required
              prop="CustomerLicenseCode"
            >
              <el-input
                v-model="InvoicingForm.CustomerLicenseCode"
                style="width: 400px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="开票金额" required prop="InvoicingMoney">
              <el-input v-model="InvoicingForm.InvoicingMoney" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-space>
              <el-form-item label="开票单位(我方)" required prop="MyLicenseID">
                <el-cascader
                  v-model="InvoicingForm.MyLicenseID"
                  :options="MyLicenseList"
                  :props="companyProps"
                  @change="handleChange"
                />
                <!-- <el-select
                  v-model="InvoicingForm.MyLicenseID"
                  style="width: 250px"
                >
                  <el-option label="新增一个开票信息" :value="0" />
                  <el-option
                    v-for="(item, index) in MyLicenseList"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select> -->
              </el-form-item>
              <el-form-item v-if="InvoicingForm.MyLicenseID == 0">
                <el-input
                  v-model="InvoicingForm.MyCompanyName"
                  style="width: 300px"
                  placeholder="请输入单位全称"
                />
                <el-input
                  v-model="InvoicingForm.MyCompanyCode"
                  style="width: 200px"
                  placeholder="请输入税号"
                />
              </el-form-item>
            </el-space>
          </el-col>
          <!-- <el-col :span="5">
            <el-form-item label="收据/发票号" required>
              <el-input
                v-model="InvoicingForm.InvoicingCode"
                style="width: 180px"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="5">
            <el-form-item>
              <el-button type="primary" @click="saveInvoicingok">
                保存开票信息
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </vab-query-form>
    <!-- 上传附件 -->
    <el-dialog v-model="NewAttach" title="上传附件" @close="attachClose">
      <el-upload
        :disabled="OrderFlowState <= 2 && pageflow !== 3"
        :file-list="InvoicingFiles"
        :multiple="true"
        action="https://api.sanjianke.com/common/Upload/upload?file=InvoicingList&type=image"
        list-type="picture-card"
        :on-success="NewSuccess"
      >
        <el-icon><Plus /></el-icon>
        <template #file="{ file }">
          <div style="height: 100%; width: 100%">
            <img
              v-if="isImage(file) == true"
              class="el-upload-list__item-thumbnail"
              :src="file.url"
              alt=""
            />
            <div
              v-else
              style="
                height: 100%;
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <div style="font-size: 25px">
                {{ isImage(file) }}
              </div>
            </div>
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="NewPreview(file)"
              >
                <el-icon><zoom-in /></el-icon>
              </span>
              <span
                v-if="OrderFlowState > 2 && pageflow === 3"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <el-icon><Delete /></el-icon>
              </span>
            </span>
          </div>
        </template>
      </el-upload>
      <template v-if="OrderFlowState >= 2 && pageflow === 3" #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="upInvoicingFiles">
            确定上传
          </el-button>
        </div>
      </template>
      <el-dialog v-model="dialogVisible" top="3vh">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 100%"
        />
      </el-dialog>
    </el-dialog>
  </el-card>
</template>

<script>
  import { getInvoicingOptions, saveInvoicingFiles } from '@/api/common'
  import { saveInvoicing } from '@/api/businessOrder'
  import { confirmInvoicing } from '@/api/businessOrderCreate'

  export default defineComponent({
    name: 'InvoicingList',
    props: {
      pageflow: {
        type: Number,
        default: 0,
      },
    },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        NewAttach: false,
        companyProps: {
          expandTrigger: 'hover',
        },
        optionMsg: {
          value: 0,
          label: '新增一个开票信息',
        },
        rules: {
          InvoicingType: [
            { required: true, trigger: 'change', message: '请选择开票类型' },
          ],
          CustomerLicenseID: [
            {
              required: true,
              trigger: 'change',
              message: '请选择合同归属公司',
            },
          ],
          dialogVisible: false,
          CustomerCompanyName: [
            {
              required: true,
              trigger: 'change',
              message: '请填写开票客户全称',
            },
          ],
          CustomerLicenseCode: [
            {
              required: true,
              trigger: 'change',
              message: '请填写纳税人识别号',
            },
          ],
          InvoicingMoney: [
            { required: true, trigger: 'change', message: '请输入开票金额' },
          ],
          MyLicenseID: [
            { required: true, trigger: 'change', message: '请选择开票单位' },
          ],
        },
        InvoicingID: 0,
        OrderID: 0,
        CustomerID: 0,
        OrderInfo: {},
        InvoicingFiles: [],
        OrderFlowState: 1,
        OrderFenqi: 0,
        listLoading: false,
        formRef: null,
        editRef: null,
        InvoicingTypes: [],
        CustomerLicenseList: [],
        MyLicenseList: [],
        InvoicingList: [],
        InvoicingForm: {
          OrderID: 0,
        },
        title: '',
      })
      const showList = (OrderInfo, list, PaymentList) => {
        state.OrderInfo = OrderInfo
        state.OrderID = OrderInfo.OrderID
        state.CustomerID = OrderInfo.CustomerID
        getOptions()
        state.OrderFenqi = OrderInfo.OrderFenqi
        state.OrderFlowState = Math.abs(OrderInfo.OrderFlowState)
        console.log(OrderInfo, 'OrderInfo发票')

        state.InvoicingForm.OrderID = OrderInfo.OrderID
        state.InvoicingForm.InvoicingID = 0
        state.InvoicingList = list
        console.log('PaymentList', PaymentList)
        if (PaymentList.length !== 0) {
          state.InvoicingForm.MyLicenseID = PaymentList[0].PaymentCompany[1]
        }
      }

      const invoicingEdit = (row) => {
        state.InvoicingForm = row
      }
      const getCustomerLicense = () => {
        if (state.InvoicingForm.CustomerLicenseID == 0) {
          state.InvoicingForm.CustomerCompanyName =
            state.OrderInfo.CustomerAllName
          state.InvoicingForm.CustomerLicenseCode = ''
        }
        if (state.InvoicingForm.CustomerLicenseID !== 0) {
          const Customer = state.CustomerLicenseList.find(
            (item) => item.LicenseID == state.InvoicingForm.CustomerLicenseID
          )
          console.log(
            state.InvoicingForm.CustomerLicenseID,
            Customer,
            'Customer'
          )
          state.InvoicingForm.CustomerCompanyName = Customer.CompanyAllName
          state.InvoicingForm.CustomerLicenseCode = Customer.LicenseCode
        }
      }

      const handleDelete = (row) => {
        if (row.InvoicingID) {
          $baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await saveInvoicing({
              OrderID: row.OrderID,
              InvoicingID: row.InvoicingID,
              delok: 1,
            })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
          })
        }
      }

      const saveInvoicingok = () => {
        console.log(state.InvoicingForm, 'InvoicingForm111')
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const { msg } = await saveInvoicing(state.InvoicingForm)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            state.InvoicingForm = {
              OrderID: 0,
            }
            state['formRef'].resetFields()
            emit('fetch-data')
          }
        })
      }
      const getOptions = async () => {
        state.listLoading = true

        const params = {
          CustomerID: state.CustomerID,
          OrderID: state.OrderID,
        }

        const {
          data: { InvoicingTypes, CustomerLicenseList, MyLicenseList },
        } = await getInvoicingOptions(params)
        state.InvoicingTypes = InvoicingTypes
        state.CustomerLicenseList = CustomerLicenseList
        state.CustomerLicenseList.forEach((item) => {
          if (item.isMain == 1) {
            state.InvoicingForm.CustomerLicenseCode = item.LicenseCode
            state.InvoicingForm.CustomerLicenseID = item.LicenseID
            state.InvoicingForm.CustomerCompanyName = item.CompanyAllName
          }
        })
        state.MyLicenseList = MyLicenseList
        state.listLoading = false
      }

      const paymentConfirm = (row) => {
        console.log(row)
        if (row.InvoicingID) {
          $baseConfirm('是否确认已经开票', null, async () => {
            const { msg } = await confirmInvoicing({
              InvoicingID: row.InvoicingID,
              InvoicingState: 1,
            })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
          })
        }
      }

      const handleChange = (value) => {
        console.log(value, 'handleChange')
      }

      const upFiles = (row) => {
        if (row.InvoicingFiles) {
          state.InvoicingFiles = JSON.parse(row.InvoicingFiles)
        }
        state.InvoicingID = row.InvoicingID

        state.NewAttach = true
        console.log(row, '2222')
      }

      // 是否是图片
      const isImage = (row) => {
        console.log(row, '搞不懂')

        if (row.raw) {
          // 临时地址
          const isType = row.raw.type.split('/')[0]
          const isTypeName = row.name.split('.')[1]
          if (isType == 'image') {
            return true
          } else {
            return isTypeName
          }
        } else {
          // 线上地址
          if (
            splitLastDot(row.url) == 'png' ||
            splitLastDot(row.url) == 'jpg' ||
            splitLastDot(row.url) == 'jpge'
          ) {
            return true
          } else {
            return splitLastDot(row.url)
          }
        }
      }
      // 反转字符串
      const splitLastDot = (msg) => {
        // 首先反转字符串
        const reversedStr = msg.split('').reverse().join('')
        // 使用split切割第一个点
        const parts = reversedStr.split('.')[0]
        // 结果反转并返回
        return parts.split('').reverse().join('')
      }

      const NewPreview = (uploadFile) => {
        // 判断是否是临时地址
        if (uploadFile.raw) {
          const isType = uploadFile.raw.type.split('/')[0]
          if (isType == 'image') {
            state.dialogImageUrl = uploadFile.url
            state.dialogVisible = true
          } else {
            window.open(uploadFile.url, '_blank')
          }
        } else {
          if (
            splitLastDot(uploadFile.url) == 'png' ||
            splitLastDot(uploadFile.url) == 'jpg' ||
            splitLastDot(uploadFile.url) == 'jpge'
          ) {
            state.dialogImageUrl = uploadFile.url
            state.dialogVisible = true
          } else {
            window.open(uploadFile.url, '_blank')
          }
        }
      }

      const NewSuccess = (response) => {
        console.log(response, 'response')

        const data = {
          url: response.data.url,
        }
        state.InvoicingFiles.push(data)
        console.log(state.InvoicingFiles, 'clickGiftAttFiles')

        ElMessage({
          message: '上传成功',
          type: 'success',
        })
      }

      const handleRemove = (row) => {
        console.log(row, ';1')

        const index = state.InvoicingFiles.findIndex((fileItem) => {
          return fileItem.url === row.url
        })
        state.InvoicingFiles.splice(index, 1)
      }

      const upInvoicingFiles = async () => {
        const dataMsg = {
          InvoicingID: state.InvoicingID,
          InvoicingFiles: state.InvoicingFiles,
        }

        const { msg } = await saveInvoicingFiles(dataMsg)
        console.log(state.InvoicingFiles, 'TaskSetFiles')
        state.NewAttach = false
        $baseMessage(msg, 'success', 'vab-hey-message-success')
        emit('fetch-data')
      }

      return {
        ...toRefs(state),
        handleRemove,
        isImage,
        showList,
        NewSuccess,
        upFiles,
        upInvoicingFiles,
        NewPreview,
        handleChange,
        paymentConfirm,
        splitLastDot,
        invoicingEdit,
        saveInvoicingok,
        getCustomerLicense,
        handleDelete,
      }
    },
  })
</script>
